"""
-------------------------------------------------
   File Name：     refreshBrowser
   Description :
   Author :       willis
   date：          2019/5/11
-------------------------------------------------
   Change Activity:
                   2019/5/11:

-------------------------------------------------

"""
__author__ = 'willis'

import logging.handlers
import logging
import sys
import os
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import webbrowser

urls = [
    [5, "https://www.baidu.com"],
]

chrome_path = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'

def log_out():
    '''
    日志输出
    :return:
    '''

    log_file = os.path.realpath(sys.argv[0]) + '.log'

    # 定义对应的程序模块名name，默认是root
    logs = logging.getLogger()
    logs.setLevel(logging.DEBUG)

    # 定义日志回滚
    logrota = logging.handlers.RotatingFileHandler(log_file, maxBytes=10 * 1024 * 1024, backupCount=20)

    # 设置日志等级
    logrota.setLevel(logging.DEBUG)

    # 日志输出到屏幕控制台
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)

    # 定义日志格式
    format = ('%(asctime)s|%(name)s|%(levelname)s|'
              '%(pathname)s|%(lineno)d|%(thread)s|%(process)s|%(message)s')

    # 实例化handler
    formatter = logging.Formatter(format)

    # 格式化handler
    logrota.setFormatter(formatter)
    console.setFormatter(formatter)

    # 添加handler
    logs.addHandler(logrota)
    logs.addHandler(console)

    # logs.debug('my is debug')
    # logs.info('my is info')
    # logs.warning('my is warning')
    # logs.error('my is error')
    # logs.critical('my is critical')
    logs.info('Loging start ...')
    return logs

def build_browser():
    # 去除全屏显示 自动控制的标题栏
    chrome_options = webdriver.ChromeOptions()
    chrome_options._arguments = ['disable-infobars']

    # chrom_option = Options()
    # chrom_option.add_experimental_option(de)

    browser = webdriver.Chrome(
        executable_path='C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe',
        chrome_options=chrome_options
    )
    print(dir(browser))

    browser.fullscreen_window()

    return browser

def refresh_web(obj):
    count = 0
    while(count<3):
        time.sleep(3)
        for url in urls:
            logs.info("{}:{}".format(url[0], url[1]))
            obj.get(url=url[1])
            # time.sleep(url[0])

            obj.find_element_by_link_text('新闻').click()
            # obj.back()  # 后退：回到百度首页
            # obj.forward()  # 前进：前进到百度新闻页面

            try:
                obj.refresh()
                logs.info("刷新成功.")
            except Exception as e:
                logs.error('刷新失败！{}'.format(e))
        count += 1

    # obj.quit()

def webbrowser_build():
    '''
    https://docs.python.org/2/library/webbrowser.html

    webbrowser.open()
        #new:0/1/2 0：同一浏览器窗口打开 1：打开浏览器新的窗口，2：打开浏览器窗口新的tab
        #autoraise=True:窗口自动增长

    如果你知道进程名称可以用taskkill
        命令：
        命令语法：taskkill / IM
        进程名
        比如：
        1，关闭谷歌浏览器：taskkill / IM chrome.exe
        2，关闭火狐浏览器：taskkill / IM firefox.exe
        3，关闭IE：taskkill / IM Iexplore.exe
        注意：一个程序可能在系统中生成多个进程。可以用tasklist命令查看系统中所有进程

        counter = 1
        #关闭谷歌浏览器，防止内存不足
        os.system('taskkill / IM chrome.exe')

    :return:
    '''

    web_urls = [
        ['jira', 'http://jira.dev.zamplus.com/login.jsp'],
        ['wiki', 'http://wiki.dev.zamplus.com/dashboard.action;jsessionid=4A3FFF0EE06B14A4BF27442374CB7E5E'],
        ['zbx_cola', '221.228.208.51:65432/zabbix/charts.php'],
        ['zbx_151', 'http://101.230.224.72:9900/zabbix/zabbix.php?action=dashboard.view&ddreset=1']
    ]

    webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path))
    webs = webbrowser.get('chrome')

    count = 0
    while(count < 2):
        for name in web_urls:
            try:
                webbrowser.register(name[0], None, webbrowser.BackgroundBrowser(chrome_path))
                webs = webbrowser.get('chrome')
                result = webs.open(name[1], new=0, autoraise=False)
                print(result)
            except Exception as e:
                logs.info(e)

            time.sleep(3)
            count = count + 1


if __name__ == '__main__':
    global logs
    logs = log_out()

    # build_browser()
    refresh_web(build_browser())
    # print(dir(webdriver))

    # webbrowser_build()


